﻿using System;
using System.Collections.Generic;

using SBPweb.RIA.Shared.Contracts.Extensibility;

namespace SBPweb.RIA.Shared.Contracts.Events
{

    public class AsyncRequestArgs<TResult> : EventArgs<TResult>
    {

        public AsyncRequestArgs()
        {
            Arguments = new ExtendableBag();
        }

        public AsyncRequestArgs(AsyncRequestHandler<TResult> completed, params object[] args)
            : this()
        {
            this.CompletedHandler = completed;

            if (args != null)
            {
                int i = 0;
                foreach (object o in args)
                {
                    this.Arguments.Put<object>((i++).ToString(), o);
                }
            }
        }

        public AsyncRequestArgs(AsyncRequestHandler<TResult> completed, ICollection<KeyValuePair<string, object>> args)
            : this()
        {
            this.CompletedHandler = completed;

            if (args != null)
            {
                foreach (KeyValuePair<string, object> kvp in args)
                {
                    this.Arguments.Put<object>(kvp.Key, kvp.Value);
                }
            }
        }

        public ExtendableBase Arguments
        {
            get;
            private set;
        }

        public AsyncRequestHandler<TResult> CompletedHandler
        {
            get;
            private set;
        }

        public void RaiseCompletedEvent(object sender, TResult result)
        {
            Result = result;
            if (CompletedHandler != null)
            {
                CompletedHandler.DynamicInvoke(sender, this);
            }
        }



    }

    public delegate void AsyncRequestHandler<TResult>(object sender, EventArgs<TResult> e);

}